import DeleteFilled from "@ant-design/icons/DeleteFilled"
import PlusOutlined from "@ant-design/icons/PlusOutlined"
import { Image } from "antd"
import classNames from "classnames"
import * as _ from "lodash"
import * as React from "react"
import { MouseEvent, useState } from "react"
import { ImageBlobsModal } from "../store/blobs/image-blobs"
import classes from "./product-images.module.scss"

interface ProductImageProps {
  className?: string
  url?: string;
  onClick?: (event: MouseEvent<HTMLDivElement>) => void
  onDelete?: () => void
  children?: React.ReactNode
}

function ProductImage(props: ProductImageProps) {
  const { children, url, onClick, onDelete, className } = props
  return (
    <div className={classNames(classes.ProductImage, className)} onClick={onClick}>
      {_.isEmpty(url) && children}
      {
        url && <>
          <Image src={url}/>
          <div className={classes.ProductImageActions}>
            <DeleteFilled onClick={e => {
              e.stopPropagation()
              if (_.isFunction(onDelete)) {
                onDelete()
              }
            }}/>
          </div>
        </>
      }
    </div>
  )
}

const MAX_PRODUCT_IMAGE_SIZE = 10

interface ProductImagesProps {
  imageUrls: string[];
  onClick?: (event: MouseEvent<HTMLDivElement>) => void
  onChange: (images: string[]) => void;
}

export default function ProductImages(props: ProductImagesProps) {
  const { imageUrls = [], onChange, onClick } = props
  const [popVisible, setPopVisible] = useState(false)

  function handleDelete(imageUrl: string) {
    onChange(_.filter(imageUrls, aImage => aImage !== imageUrl && !_.isEmpty(aImage)))
  }

  return (
    <div className={classes.ProductImages}>
      <ImageBlobsModal selectable
                       visible={popVisible}
                       onSelect={blobs => {
                         const newUrls = _.chain(blobs).map(({ url = "" }) => url).value()
                         onChange(_.slice([...imageUrls, ...newUrls], 0, MAX_PRODUCT_IMAGE_SIZE))
                         setPopVisible(false)
                       }}
                       onCancel={() => setPopVisible(false)}/>
      {
        _.map(imageUrls, (imageUrl, index) => (
          <ProductImage key={imageUrl + index} url={imageUrl}
                        onClick={onClick}
                        onDelete={() => handleDelete(imageUrl)}/>
        ))
      }
      {
        _.size(imageUrls) < MAX_PRODUCT_IMAGE_SIZE && <>
          <ProductImage className={classes.ProductAddImage} onClick={() => setPopVisible(true)}>
            <PlusOutlined style={{ fontSize: "24px", color: "#969799" }}/>
          </ProductImage>
        </>
      }
    </div>
  )
}

